// pages/prize/prize.js
import regeneratorRuntime from '../../utils/regenerator-runtime/runtime-module.js'
import api from '../../utils/api.js'
const { $Toast } = require('../../iview/base/index')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: {},
    score: 0,
    order: 0,
    date_strat: 0,
    date_in: 0,
    date_end: 0,
    countdown_time: 0,
    prize: null,
    prize_1: null,
    noStart: false,
    countdown: false,
    end: false,
    prize_rank: null,
    format: 'hh:mm:ss',
    attention: null,
    attentionData: null,
    visible: false,
    actions: [
      {
        name: '取消'
      },
      {
        name: '点击关注',
        color: '#ff9900'
      }
    ],
    imgalist: [],
    visible_1: false,
    actions_1: [
      {
        name: '取消'
      },
      {
        name: '领取',
        color: '#ff9900'
      }
    ],
    visible_2: false,
    actions_2: [
      {
        name: '取消'
      },
      {
        name: '去设置',
        color: '#ff9900'
      }
    ],
    receiveData: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
    this.onShow()
    let sent_count_data = await api.authRequest("prizes")
    let order = sent_count_data.data.meta.user.rank.order
    let responseData = sent_count_data.data.data.map((item) => {
      let ranks = item.rank.split('-')
      if (ranks.length === 1) {
        item.aviable = order === parseInt(ranks[0])
        return item
      }

      item.aviable = true

      if (ranks[0] && order < ranks[0]){
        item.aviable = false
      }

      if (ranks[1] && order > ranks[1]) {
        item.aviable = false
      }

      if (!ranks[1]){
        item.rank = ranks[0].toString() + '+'
      }
      return item
    })

    let count = 3 - (responseData.length - 1) % 3
    if (count > 0 && count < 3) {
      for (let i = 0; i < count; i++) {
        responseData.push({})
      }
    }


    this.setData({
      prize: sent_count_data.data.data,
      prize_1: responseData.shift(),
      score: sent_count_data.data.meta.user.rank.score,
      order: sent_count_data.data.meta.user.rank.order,
      date_strat: sent_count_data.data.meta.current_date,
      date_in: sent_count_data.data.meta.moon_cake_end_date,
      countdown_time: sent_count_data.data.meta.moon_cake_prize_end_date - sent_count_data.data.meta.current_date,
      date_end: sent_count_data.data.meta.moon_cake_prize_end_date,
      res: responseData,
      attentionData: sent_count_data.data.meta.user.follow_official_account,
      userInfo: sent_count_data.data.meta.user,
      receiveData: sent_count_data.data.meta.receive
    })
    this.isFollowed()
    
    this.timeShow()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    this.setData({
      visible: false,
      visible_2: false
    })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  },
  
  onShow () {
    this.bottomNavigation = this.selectComponent("#prize")
    this.bottomNavigation._displayShow()
  },

  address (e) {
    let id = e.currentTarget.id
    let _url = e.currentTarget.dataset.url
    let that = this
    wx.setStorageSync('url', _url)
    if (that.data.attention) {
      if (e.currentTarget.dataset.receive) {
        if (e.currentTarget.dataset.type === "real") {
          if (that.data.receiveData === null ) {
            wx.chooseAddress({
              success: async function (res) {
                let resphone = await api.authRequest({
                  method: 'POST',
                  url: 'prizes/' + id + '/receive',
                  data: {
                    province: res.provinceName,
                    city: res.cityName,
                    district: res.countyName,
                    address: res.detailInfo,
                    zip: res.postalCode,
                    contact_name: res.userName,
                    contact_phone: res.telNumber
                  }
                })
                console.log(resphone)
                if (resphone.statusCode === 204) {
                  wx.showToast({
                    title: '提交成功，近期客服会与您联系！',
                    icon: 'none',
                    duration: 3000
                  })
                }
              },
              fail () {
                that.setData({
                  visible_2: true
                })
              }
            })
          } else {
            wx.showToast({
              title: '您已经领取过了！',
            })
          }
          
        } else {

          api.authRequest({
            method: 'POST',
            url: 'prizes/' + id + '/receive',
            data: {

            }
          })
          this.setData({
            visible_1: true,
            imgalist: [e.currentTarget.dataset.url]
          })
         
        }
      } else {
        wx.showToast({
          title: '无资格领取',
          icon: 'none'
        })
      }
    } else {
      this.setData({
        visible: true
        })
      }  
    },

    timeShow () {
      if (this.data.date_strat < this.data.date_in) {
        this.setData({
          noStart: true
        })

      } else if (this.data.date_strat < this.data.date_end) {
        this.setData({
          countdown: true
        })
      } else if (this.data.date_strat > this.data.date_end) {
        this.setData({
          end: true
        })
      }
    },
    
    isFollowed () {
      if (this.data.attentionData) {
        this.setData({
          attention: true
        })
      } else {
        this.setData({
          attention: false
        })
      }
    },

  focusClick({ detail }) {
      const index = detail.index
      if (index === 0) {
        this.setData({
          visible: false
        })
      } else if (index === 1) {
        this.setData({
          attention: true
        })
        wx.navigateTo({
          url: '/pages/nopublic/nopublic',
        })
      }
    },

  focusClick_1 ({detail}) {
      const index = detail.index
      if (index ===0 ) {
        this.setData({
          visible_1: false
        })
      } else if (index === 1) {
        wx.previewImage({
          current: this.data.imgalist,
          urls: this.data.imgalist
        })
      }
  },
  focusClick_2 ({detail}) {
      const index = detail.index
      if (index ===0 ) {
        this.setData({
          visible_2: false
        })
      } else if (index === 1) {
        let that = this
        wx.getSetting({//先获取用户当前的设置
          success(res) {
            if (!res.authSetting['scope.address']) {
              wx.openSetting({
                sucess: res => {
                }
              })
            } else {
              wx.chooseAddress({
                success: async function (res) {
                  let resphone = await api.authRequest({
                    method: 'POST',
                    url: 'prizes/' + id + '/receive',
                    data: {
                      province: res.provinceName,
                      city: res.cityName,
                      district: res.countyName,
                      address: res.detailInfo,
                      zip: res.postalCode,
                      contact_name: res.userName,
                      contact_phone: res.telNumber
                    }
                  })
                  if (resphone.statusCode === 204) {
                    wx.showToast({
                      title: '提交成功，近期客服会与您联系！',
                      icon: 'none',
                      duration: 3000
                    })
                  }
                },
                fail() {
                  that.setData({
                    visible_2: true
                  })
                  
                }
              })
            }
          }
        })
      }
  },
  focus_button () {
    this.setData({
      attention: true
    })
  },
  noStart () {
    wx.showToast({
      title: '兑奖活动还未开始，请您9月25日根据排名再来兑换相应奖品',
      icon: 'none',
      duration: 3000
    })
  },
  end () {
    wx.showToast({
      title: '兑奖活动已结束，感谢您的参与！',
      icon: 'none'
    })
  }
  })